<template>
    <main class="content pb-70">
        <header><van-icon name="arrow-left" @click="back" /> <span> {{ title }}</span></header>
        <div class="body-content">
            <div class="query-list">
                <div class="query-list-title">请您选择以下方式输入线索信息，小微会在最快时间内为您匹配类似案例。</div>
                <div class="list-info" style="color: rgb(66,146,255);" @click="changeInputMode(true)">语音输入 </div>
                <div class="list-info" style="color: rgb(66,146,255);" @click="changeInputMode(false)">文字输入</div>
            </div>
            <template v-if="state.contentList.length !== 0">
                <div v-for="(outItem, index) in state.contentList" :key="index">
                    <ShowTime :time="outItem.time"></ShowTime>
                    <ShowSendMessage :getMessageText="outItem.getMessageText"></ShowSendMessage>
                    <!-- <div class="statement" v-if="isStatement" @click="query(4)">
                        <span>
                            10s
                            <van-icon name="volume-o" />
                        </span>
                        <span v-if="isChangeText">
                            我局接举报称:上海羊晨羊晓信息技术有限公司官网主页(http://www.kezaihui.com)上发布“餐饮行业顶尖的流量运营解决方案供应商，以专业领先的科技和及时温暖的服务为全天下餐饮创业者打CALL”的宣传欺骗消费者，要求查处。
                        </span>
                    </div> -->
                    <div class="mb-20" v-if="outItem.length">
                        <HighLight :text="`根据您提供的伪容，小微共匹配出类似的违法行为,${outItem.length}个，相似案例可通过网页端登录查看。`"
                            :keywords="`${outItem.length}个`"></HighLight>
                    </div>
                    <template v-if="route.query.type == 1">
                        <div class="query-list" v-for="item in outItem.data" :key="item.code" :id="'title_id' + index">
                            <div class="info-head">
                                <van-icon style="font-size: 22px;" name="completed-o" />
                                <span class="info-head-info">行为描述</span>
                                <div class="info-head-match">匹配度:<span>{{ parseFloat(item.similarity.toFixed(2))
                                        }}%</span>
                                </div>
                            </div>
                            <div class="list-info">{{ item.remark }}</div>
                        </div>
                    </template>
                    <template v-else>
                        <div style="margin-bottom:10px">
                            {{ outItem.data && outItem.data.actName }}
                        </div>
                        <div class="query-list" v-if="outItem.data" :class="{ 'fold': outItem.fold }"
                            :id="'title_id' + index">
                            <div class="info-head">
                                <div>
                                    <van-icon style="font-size: 22px;" name="completed-o" />
                                    <span class="info-head-info">裁量基准</span>
                                </div>
                                <van-icon name="arrow-down" v-if="outItem.fold" @click="toggleItem(outItem)" />
                                <van-icon name="arrow-up" v-else @click="toggleItem(outItem)" />
                            </div>
                            <div style="margin-bottom: 20px;" v-for="item in state.benchmarkList"
                                :key="item.factorType">
                                <div class="list-info" style="font-weight: 600;">
                                    <div>{{ item.name }}</div>
                                </div>
                                <div class="list-info">
                                    <span style="width: 70%;">{{ item.lightFactorDescription }}</span>
                                    <van-checkbox v-model="item.checked1" @change="checkedChange">从轻</van-checkbox>
                                </div>
                                <div class="list-info">
                                    <span style="width: 70%;">{{ item.normalFactorDescription }}</span>
                                    <van-checkbox v-model="item.checked2" @change="checkedChange">一般</van-checkbox>
                                </div>
                                <div class="list-info">
                                    <span style="width: 70%;">{{ item.heavyFactorDescription }}</span>
                                    <van-checkbox v-model="item.checked3" @change="checkedChange">从重</van-checkbox>
                                </div>
                            </div>
                        </div>
                    </template>
                    <div class="query-list" v-if="route.query.type == 2">
                        <div class="query-list-title" style="border-left: 4px solid #5384d2;">辅助分析<span
                                @click="getAssisttantPunishDesc(outItem.words, outItem.illigelActId)"
                                style="color:#5384d2;margin-left: 10px;">查询</span>
                        </div>
                        <div class="list-info">{{ outItem.getBenhMarkTxt }}</div>
                    </div>
                </div>
            </template>
            <WiLoading v-if="loading"></WiLoading>
            <div class="query-list" v-if="isChangeText">
                <div class="query-list-title" style="border-left: 4px solid #5384d2;">智能辅助回访</div>
                <div class="list-info">检索的违法行为不是想要的，重新推荐? <van-icon name="arrow" /></div>
                <div class="list-info">识别的语音文案不够准确，需要重新识别? <van-icon name="arrow" /></div>
            </div>
        </div>
        <ActionBar ref="actionBar" @sendMassage="parse" :loading="loading"></ActionBar>
    </main>
</template>
<script setup>
import { nextTick, onMounted, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
    assisttantParse,
    getAssisttantAct,
    getAssisttantCase,
    discretionaryBenchmark,
    assisttantPunishDesc,
    lawStd,
    chatSessionCollect
} from "@/api";
import { showFailToast } from 'vant';
import { formatDate } from "@/utils/ruoyi";
import ShowTime from "./components/ShowTime.vue";
import ShowSendMessage from "./components/ShowSendMessage.vue";
import HighLight from "./components/HighLight.vue";

import ActionBar from "./components/ActionBar.vue";
import { reactive } from "vue";
const router = useRouter()
const route = useRoute()
const title = ref('违法行为识别')
const back = () => {
    router.go(-1)
}
const isStatement = ref(false)
const isQueryInfo = ref(false)
const isChangeText = ref(false)
const actionBar = ref(null)
const changeInputMode = (flag) => {
    actionBar.value.changeSpeak(flag)
}
const loading = ref(false)
const state = reactive({
    caseDatas: [],
    benchmarkList: [],
    benchmarkTotal: [],
    fuzhuDate: {},
    words: [],
    contentList: []
})

const toggleItem = (item) => {
    item.fold = !item.fold
}

const query = (type) => {
    if (type === 1) {
        isStatement.value = true
    } else if (type === 4) {
        isQueryInfo.value = true
        isChangeText.value = true
    }
}
const getDiscretionaryBenchmark = (illigelActId) => {
    discretionaryBenchmark(illigelActId).then(d => {
        d.items.forEach(item => {
            item.checked1 = false
            item.checked2 = false
            item.checked3 = false
        })
        state.benchmarkList = d.items;
    })
}
const getBenchMarkIndex = ref('从轻')
const getAssisttantPunishDesc = (words, illigelActId) => {
    assisttantPunishDesc({
        words,
        domains: [],
        illigelActId,
        stats: [
            {
                groupfield: '处罚情况',
                name: '处罚情况'
            }, {
                groupfield: '罚款区间',
                name: '罚款区间'
            }
        ]
    }).then((res) => {
        for (const key in res.data) {
            if (Object.hasOwnProperty.call(res.data, key)) {
                if (res.data[key] == null) {
                    res.data[key] = 0
                }
            }
        }
        state.fuzhuDate = res.data
        state.contentList.forEach(item => {
            if (item.illigelActId === illigelActId) {
                item.getBenhMarkTxt = `建议${getBenchMarkIndex.value} 类案${state.fuzhuDate.total}件,比例:${Math.round(state.fuzhuDate.total / res.dataTotal.total)
                    }%, 平均处罚金额: ${state.fuzhuDate.avg.toFixed(2)}万元, 处罚金额中位数: ${state.fuzhuDate.media.toFixed(2)}万元, 处罚金额最大值: ${state.fuzhuDate.max.toFixed(2)}万元, 处罚金额最小值: ${state.fuzhuDate.min.toFixed(2)}万元`
            }
        })
    })
}
const checkedChange = () => {
    let height = 0, low = 0;
    state.benchmarkList.forEach(item => {
        if (item.checked1) {
            low++
        }
        if (item.checked3) {
            height++
        }
    })
    if (low - height > 0) {
        getBenchMarkIndex.value = '从轻'
    } else if (low - height < 0) {
        getBenchMarkIndex.value = '从重'

    } else {
        getBenchMarkIndex.value = '一般'
    }
}
const queryGetAssisttantAct = async (words) => {
    const data = await getAssisttantAct({
        words,
        domains: []
    })
    if (data.hint.items.length === 0) {
        showFailToast('暂未匹配出类似案例');
    } else {
        const lastItem = state.contentList[state.contentList.length - 1]
        lastItem.words = words
        lastItem.data = data.hint.items ? data.hint.items.sort((a, b) => b.similarity - a.similarity) : []
        lastItem.length = data.hint.items.length
    }
}
const queryGetAssisttantCase = async (words) => {
    const data = await getAssisttantCase({
        words,
        domains: []
    })
    if (data.caseDatas.length === 0) {
        showFailToast('暂未匹配出类似案例');
    } else {
        const lastItem = state.contentList[state.contentList.length - 1]
        lastItem.words = words
        lastItem.data = data.caseDatas[0]
        lastItem.length = data.caseDatas.length
        lastItem.illigelActId = data.caseDatas[0].actNo
        setChatSessionCollect(data.caseDatas[0].caseId)

        getDiscretionaryBenchmark(data.caseDatas[0].actNo)

    }
}
/** 1. 识别 */
const parse = async (val) => {
    state.contentList.push({
        time: formatDate(new Date(), 'HH:mm:ss'),
        getMessageText: val
    })
    loading.value = true
    try {
        const data = await assisttantParse(val)
        const words = []
        const arr = data.filter(item => item.effective)
        arr.forEach(item => {
            words.push(item.word)
        });
        state.words = words
        if (route.query.type == 1) {
            await queryGetAssisttantAct(words)
        } else {
            await queryGetAssisttantCase(words)
        }
        await nextTick()
        const el = document.getElementById('title_id' + (state.contentList.length - 1))
        window.scrollTo(0, el.offsetTop)
        loading.value = false
    } catch (e) {
        loading.value = false
    }
};
function setChatSessionCollect(id) {
    chatSessionCollect({
        id,
        type: "0",
    }).then(res => {
        if (res.code == 0) {

        }
    })
}
onMounted(() => {
    if (route.query.type == 1) {
        title.value = '违法行为识别'
    } else {
        title.value = '行政处罚建议'
    }
})
</script>
<style lang="scss" scoped>
.content {
    min-height: 100vh;
    background-color: #f9f9f9;

    header {
        display: flex;
        align-items: center;
        padding: 0 20px;

        font-size: 20px;
        font-weight: 600;
        height: 60px;

        .help-icon {
            display: inline-block;
            width: 30px;
            height: 30px;
            margin-right: 10px;
            background: url('../assets/imgs/help_icon.png') no-repeat;
            background-size: 100% 100%;
        }

        span {
            display: flex;
            align-items: center;
            margin: auto;
        }
    }

    .body-content {
        position: relative;
        padding: 0 20px;
        margin-top: 5px;
        // height: calc(100vh - $headerHeight - $footerHeight);
        overflow: auto;

        .query-list {
            margin-bottom: 20px;
            padding: 10px 5px 30px 10px;
            border-radius: 10px;
            background-color: #fff;

            .info-head {
                display: flex;
                align-items: center;
                justify-content: space-between;
                height: 40px;
                padding-right: 20px;
                color: $activeColor;

                .info-head-info {
                    margin-left: 10px;
                    margin-right: 40px;
                    font-weight: 600;
                }

                .info-head-match {
                    padding: 3px 10px;
                    margin-right: 20px;
                    border-radius: 12px;
                    background: #d7e8ff;
                    color: #000;
                }
            }

            .query-list-title {
                font-size: 16px;
                font-weight: 600;
                padding-left: 10px;
            }

            .list-info {
                margin-top: 5px;
                padding-left: 10px;
                padding-right: 20px;
                display: flex;
                justify-content: space-between;

                .info-label {
                    display: inline-block;
                    min-width: 80px;
                    color: #000;
                    font-weight: 600;
                }

                p {
                    margin: 0;
                }
            }
        }

        .fold {
            height: 100px;
            overflow: hidden;
        }


    }
}
</style>